package com.c212.manager.controller;

import com.c212.manager.bean.ArticleEntity;
import com.c212.manager.bean.form.ArticleForm;
import com.c212.manager.repository.ArticleRepository;
import com.c212.manager.utils.UserContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    ArticleRepository articleRepository;


    /**
     * 保存/更新
     *
     * @param form
     * @param bindingResult
     * @param map
     * @return
     */
    @PostMapping("/save")
    public ModelAndView save(@Valid ArticleForm form,
                             BindingResult bindingResult,
                             Map<String, Object> map) {
        if (bindingResult.hasErrors()) {
            map.put("msg", bindingResult.getFieldError().getDefaultMessage());
            map.put("url", "/article/index");
            return new ModelAndView("common/error", map);
        }

        ArticleEntity articleEntity = new ArticleEntity();
        try {
            if (form.getId() != null) {
                articleEntity = articleRepository.findById(form.getId()).get();
            }

            if (articleEntity.getId() == null) {
                articleEntity.setCreatedBy(UserContext.getUser());
                articleEntity.setCreatedDate(LocalDateTime.now());
            } else {
                articleEntity.setLastModifiedBy(UserContext.getUser());
                articleEntity.setLastModifiedDate(LocalDateTime.now());
            }

            BeanUtils.copyProperties(form, articleEntity);
            articleRepository.save(articleEntity);
        } catch (Exception e) {
            map.put("msg", e.getMessage());
            map.put("url", "/article/index");
            return new ModelAndView("/common/error", map);
        }
        map.put("msg", "添加成功");
        map.put("url", "/article/list");
        return new ModelAndView("/common/success", map);
    }

//    @GetMapping("/save")
//    @ResponseBody
//    public Object save() {
//
//        ArticleEntity articleEntity = new ArticleEntity();
//
//        articleEntity.setTitle("test-title" + new Random().nextInt(100));
//        articleEntity.setContent("我是文章体" + new Random().nextInt(100));
//
//        articleEntity.setCreatedDate(LocalDateTime.now());
//        articleEntity.setCreatedBy(UserContext.getUser());
//
//        return articleRepository.save(articleEntity);
//
//    }

    /**
     * 展示
     *
     * @param articleId
     * @param map
     * @return
     */
    @GetMapping("/index")
    public ModelAndView index(@RequestParam(value = "articleId", required = false) Integer articleId,
                              Map<String, Object> map) {
        if (articleId != null) {
            ArticleEntity articleEntity = articleRepository.findById(articleId).get();
            map.put("articleEntity", articleEntity);
        }

        return new ModelAndView("/article/index", map);
    }

    @GetMapping("/list")
    public ModelAndView list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                             @RequestParam(value = "size", defaultValue = "10") Integer size,
                             Map<String, Object> map) {
        PageRequest request = new PageRequest(page - 1, size, Sort.Direction.DESC, "createdDate");

        Page<ArticleEntity> articleEntityPage = articleRepository.findAll(request);

        map.put("articlePage", articleEntityPage);
        map.put("currentPage", page);
        map.put("size", size);

        return new ModelAndView("/article/list", map);
    }
}
